import { defineComponent, ref, watch } from "vue";
import "./index.less";
import AMapView from "../AMap";
import { IAMapRef } from "../AMap/types";
import CardView from "../CardView";
import TextView from "../TextView";
import RowView from "../RowView";
import {
  getSize,
  getUserInfoUrl,
  getUserType,
  getUserTypeValue,
} from "@/command/apiTool";
import { useDetail } from "@/hooks";
import { pairMapProps } from "./types";
import { getAction } from "@/command/netTool";
import ButtonView from "../ButtonView";
import focus from "./asset/focusX1.png";
import normal from "./asset/normalX1.png";
import listIcon from "./asset/listIcon.png";

import * as vant from "vant";
import { useRouter } from "vue-router";

const { showSuccessToast } = vant;
export default defineComponent({
  name: "",
  props: pairMapProps,
  setup(_) {
    const router = useRouter();
    const amapRef = ref<IAMapRef>();
    const showModal = ref(false);
    let markers: any[] = [];
    let selectMarker: any = null;
    const position = localStorage.getItem("positionData") as string;
    const positionJSON = JSON.parse(position) as {
      latitude: string;
      longitude: string;
    };
    // 小户列表
    const [queryJdListByDh, detailConfig] = useDetail(
      getUserInfoUrl({
        dh: "/api/H5/richHelpFormationApply/large/queryJdDtListByDh",
        xh: "/api/H5/richHelpFormationApply/small/queryJdDtListByXh",
      }),
      []
    );

    // 点位详情
    const pointInfo = ref({
      entityName: "",
      productTypeName: "",
      jl: "",
      bx: "",
      address: "",
      flag: "",
      id: "",
    });

    // 监听参数变化
    watch(
      () => _.modelValue,
      (newValue) => {
        detailConfig.refresh(newValue);
      },
      {
        deep: true,
      }
    );

    const openPoint = (info: any) => {
      getAction(
        getUserInfoUrl({
          dh: "/api/H5/richHelpFormationApply/large/queryClik",
          xh: "/api/H5/richHelpFormationApply/small/queryClik",
        }).url,
        {
          farmerId: info.id,
          lat: positionJSON.latitude,
          lng: positionJSON.longitude,
        }
      ).then((e) => {
        pointInfo.value = e;
      });
    };

    const getIcon = (img: any) => {
      // 创建一个 Icon
      var startIcon = new AMap.Icon({
        // 图标尺寸
        size: new AMap.Size(25, 34),
        // 图标的取图地址
        image: img,
        // 图标所用图片大小
        imageSize: new AMap.Size(135, 40),
        // 图标取图偏移量
        imageOffset: new AMap.Pixel(-9, -3),
      });
      return startIcon;
    };
    watch(
      () => queryJdListByDh.value,
      (newValue) => {
        markers.forEach((e) => amapRef.value?.map().remove(e));
        markers = [];
        newValue.forEach((e: any) => {
          var marker = new AMap.Marker({
            // size: new AMap.Size(25, 34),
            // 图标的取图地址
            // image: normal,
            // 图标所用图片大小
            // iconSize: [25, 34],
            // 图标取图偏移量
            imageOffset: new AMap.Pixel(-9, -3),
            // icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            // icon: null,
            icon: normal,
            position: [e.lng, e.lat],
            anchor: "bottom-center",
            // imageSize: new AMap.Size(25, 34),
          });
          marker.on("click", () => {
            if (selectMarker == null) {
              selectMarker = marker;
            } else {
              selectMarker.setIcon(normal);
              selectMarker = marker;
            }
            marker.setIcon(focus);
            openPoint(e);
            showModal.value = true;
          });
          markers.push(marker);
          amapRef.value?.map().add(markers);
        });
        amapRef.value?.map().setFitView();
      }
    );
    const getButtonName = () => {
      if (getUserType() == "1") {
        return pointInfo.value.flag == "0" ? "邀请结对" : "取消结对";
      } else {
        return pointInfo.value.flag == "0" ? "申请结对" : "取消结对";
      }
    };
    const onButtonClick = () => {
      getAction(
        getUserInfoUrl({
          xh: "/api/H5/richHelpFormationApply/small/apply",
          dh: "/api/H5/richHelpFormationApply/large/apply",
        }).url,
        {
          farmerId: pointInfo.value.id,
          applyType: pointInfo.value.flag == "0" ? "1" : "2",
        }
      ).then(() => {
        showSuccessToast(
          pointInfo.value.flag == "0" ? "结对成功" : "取消结对成功"
        );
        showModal.value = false;
      });
    };
    const card1 = () => {
      return (
        <CardView title={pointInfo.value.entityName}>
          <div
            class="flex justify-between relative"
            onClick={() =>
              router.push(`/formationDetail?id=${pointInfo.value.id}`)
            }
          >
            <div class="flex flex-col w-full">
              <TextView>{pointInfo.value.productTypeName}</TextView>
              <TextView class="!text-[#333333] font-bold">
                种植品种:{pointInfo.value.address}
              </TextView>
              <RowView class="justify-between">
                <TextView>
                  <span>距你{pointInfo.value.jl}</span>
                  <span class={"ml-4"}>步行{pointInfo.value.bx}</span>
                </TextView>
                <ButtonView text={getButtonName()} onClick={onButtonClick} />
              </RowView>
            </div>
          </div>
        </CardView>
      );
    };
    const card2 = () => {
      const data = Array(10)
        .fill("")
        .map(
          (e) =>
            "https://img0.baidu.com/it/u=455228103,934359577&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1680714000&t=147f6adbfee00264b569da44cc4bb1ab"
        );
      return (
        <CardView
          title="现场照片"
          right={() => <span>查看更多</span>}
          class="mt-[12px]"
        >
          <div class="overflow-x-scroll flex ">
            {data.map((e) => {
              return (
                <img
                  class="w-[85px] h-[85px] mr-[10px]"
                  style={{ borderRadius: getSize(8) }}
                  src={e}
                />
              );
            })}
          </div>
        </CardView>
      );
    };
    const renderModal = () => {
      if (!showModal.value) return null;
      return (
        <div
          class={[
            "absolute right-0 left-0 bottom-0  z-10 mb-[10px]",
            "amap-animation",
          ]}
        >
          {card1()}
        </div>
      );
    };
    const renderListIcon = () => {
      return (
        <img
          src={listIcon}
          class={"listIcon"}
          onClick={() => router.push("/partneredList")}
        />
      );
    };
    return () => {
      return (
        <div class="relative flex flex-col flex-1">
          <AMapView ref={amapRef} class="flex-1 h-full" />
          {renderModal()}
          {renderListIcon()}
        </div>
      );
    };
  },
});
